package com.yao.sys.service.impl;


import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yao.common.enums.SysErrorEnum;
import com.yao.common.exception.BusinessException;
import com.yao.sys.entity.AccountEntity;
import com.yao.sys.entity.dto.AccountDto;
import com.yao.sys.mapper.AccountMapper;
import com.yao.sys.service.AccountService;
import org.springframework.stereotype.Service;

/**
* 账户表 接口实现
*
* @author autoCode
* @version 1.0.0-SNAPSHOT
* @date 2019-12-09
*/
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, AccountDto> implements AccountService{

    @Override
    public AccountEntity add(AccountDto model) {
        AccountDto one = this.getOne(this.queryWrapper(model));

        if(null != one){
            Console.error("新增失败,已经存在相同的手机号码:{}或账户名称:{}", model.getPhone(), model.getAccountName());
            throw new BusinessException(SysErrorEnum.ERROR);
        }
        this.save(model);
        return model;
    }


    @Override
    public boolean modify(AccountDto model) {
        return this.updateById(model);
    }


    @Override
    public boolean deleteById(Integer id) {
        AccountEntity one = this.getById(id);
        if(null == one){
            throw new BusinessException("不存在可被删除的数据.id = "+id);
        }
        return this.removeById(id);
    }

    private LambdaQueryWrapper<AccountDto> queryWrapper(AccountDto model){
        LambdaQueryWrapper<AccountDto> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(StrUtil.isNotBlank(model.getPhone()), AccountEntity::getPhone, model.getPhone())
                .or()
                .eq(StrUtil.isNotBlank(model.getAccountName()), AccountEntity::getAccountName, model.getAccountName());


        return queryWrapper;
    }
}